/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.training.scheduled;

import com.koron.common.bean.StaffBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.common.web.Util;
import com.koron.personal.domain.MyCertificate;
import com.koron.personal.mapper.MyCertificateMapper;
import com.koron.system.domain.Message;
import com.koron.system.mapper.MessageMapper;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
@EnableScheduling
public class CertificateScheduled {

    @Autowired
    private Util util;

    private final static  Logger logger = LoggerFactory.getLogger(CertificateScheduled.class);

    private final long oneDayMilliSecond = 24l*60l*60l*1000l;

    private final long oneMonthMilliSecond = 30l*24l*60l*60l*1000l;

    @Scheduled(cron = "0 0 8 * * ?")
    public void noticeCertificate(){
        try(SessionFactory factory = new SessionFactory()){
            List<MyCertificate> myCertificates = factory.getMapper(MyCertificateMapper.class).queryByCondition(null, null, null,null);
            List<Message> messages = new ArrayList<>();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日");
            for(MyCertificate certificate : myCertificates){
                long time = certificate.getPeriod().getTime() - new Date().getTime() - oneMonthMilliSecond;
                if(time >= 0 && time <= oneDayMilliSecond){
                    Message message = new Message();
                    message.setId(DefaultIdGenerator.getInstance().generateLongId());
                    message.setAddTime(new Date());
                    message.setIsRemove(0);
                    message.setIsRead(0);
                    message.setReceiverCode(certificate.getStaffCode());
                    String format = dateFormat.format(certificate.getPeriod());
                    StringBuilder sb = new StringBuilder();
                    sb.append("证照名:").append(certificate.getCertificateName()).append("，失效日期：").append(format);
                    message.setAddUser("管理员");
                    message.setContent(sb.toString());
                    message.setTitle("您有一个证照即将过期");
                    messages.add(message);
                    //发送企业微信
                    String managerWxUserId = null;
                    List<StaffBean> list = (List<StaffBean>) util.staff(certificate.getStaffCode(), null).getData();
                    if (null != list && list.size() > 0) {
                        managerWxUserId = list.get(0).getOpenid();
                    }
                    if (StringUtils.isNotEmpty(managerWxUserId)) {
                        StringBuffer sb1 = new StringBuffer();
                        sb1.append("温馨提示:\n您有一个证照即将过期，请及时更新\n证照名：").append(certificate.getCertificateName()).append("\n失效日期：").append(format).append("\n如已处理,请忽略本消息");
                      }
                }
            }
            if(!messages.isEmpty()){
                factory.getMapper(MessageMapper.class).batchInsert(messages);
            }
        }catch (Exception e){
            logger.error(e.getMessage(),e);
        }
    }
}
